# 作业：
# 一、定义一个学生Student类。有下面的类属性：
# 1 姓名 name
# 2 年龄 age
# 3 成绩 score（语文，数学，英语) [每课成绩的类型为整数]
# 类方法：
#  1 获取学生的姓名：get_name() 返回类型:str
# 2 获取学生的年龄：get_age() 返回类型:int
# 3 返回3门科目中最高的分数。get_course() 返回类型:int
# 4 将每个实例学生对象写进txt文件里，要持久保存
# 举例：{"姓名":"a","年龄":29,"成绩":{"语文":99,"数学":100,"英语":85}
# 5 获取所有学生的信息
# 写好类以后，可以定义2个同学测试下:
class Student:
    def __init__(self,name,age,score:list):
        self.name = name
        self.age = age
        self.score = score
        str1 = "{'姓名':%s,'年龄':%s,'成绩':{'语文':%s,'数学':%s,'英语':%s}}\n" % (
            self.name, self.age, self.score[0], self.score[1], self.score[2])
        with open('1.txt','r',encoding='utf-8') as f:
            all = f.readlines()
        if str1 not in all:
            with open('1.txt','a',encoding='utf-8') as f:
                f.write(str1)
    def get_name(self):
        return self.name
    def get_age(self):
        return self.age
    def get_course(self):
        max_course=self.score[0]
        for i in self.score:
            if i>max_course:
                max_course=i
        return f"返回的最高的分数是{max_course}"


class Student:
    def __init__(self,name,age,score:list):
        self.name = name
        self.age = age
        self.score = score
        str1 = "{'姓名':%s,'年龄':%s,'成绩':{'语文':%s,'数学':%s,'英语':%s}}\n" % (
            self.name, self.age, self.score[0], self.score[1], self.score[2])
        with open('1.txt','r',encoding='utf-8') as f:
            all = f.readlines()
        if str1 not in all:
            with open('1.txt','a',encoding='utf-8') as f:
                f.write(str1)
    def get_name(self):
        return self.name
    def get_age(self):
        return self.age
    def get_course(self):
        max_score = self.score[0]
        for i in self.score:
            if i > max_score:
                max_score = i
        return f'返回3门科目中最高的分数是：{max_score}'
    def get_all_studentInfo(self):
        with open('1.txt', 'r', encoding='utf-8') as f:
            all_data = f.readlines()
        for i,k in enumerate(all_data):
            print(f'第{i+1}个学生姓名为：{k}')
if __name__ == '__main__':
    s1 = Student('张三', 19, [98, 99, 103])
    s2 = Student("李四", 99, [109, 89, 77])
    print(s1.get_name())
    print(s1.get_age())
    print(s1.get_course())
    s1.get_all_studentInfo()

# 二、定义一个字典类：dictclass。完成下面的功能：
# 1 删除某个key
# 2 判断某个键是否在字典里，如果在返回键对应的值，不存在则返回"not found"
# 3 返回键组成的列表：返回类型;(list)
# 4 合并字典，并且返回合并后字典的values组成的列表。返回类型:(list)\
class dictclass:
    def __init__(self,dict_obj:dict):
        self.dict_obj = dict_obj
    def del_key(self,key):
        if key in self.dict_obj:
            del self.dict_obj[key]
            return f"删除：{key}成功！"
        else:
            return f"not found"
    def key_list(self):
        return list(self.dict_obj.keys())
    def update_dict(self,dict1):
        self.dict_obj.update(dict1)
        return list(self.dict_obj.values())
if __name__ == '__main__':
    d1 = dictclass({"姓名":"张三",'年龄':19})
    print(d1.del_key('姓名'))
    print(d1.key_list())
    print(d1.update_dict({"地址": "沈阳"}))


# 三、定义一个列表的操作类：Listinfo
# 包括的方法:
# 1 列表元素添加: add_key(keyname) [keyname:字符串或者整数类型]
# 2 列表元素取值：get_key(num) [num:整数类型]
# 3 列表合并：update_list(list) [list:列表类型]
# 4 删除并且返回最后一个元素：del_key()
class Listinfo:
    def __init__(self,list_obj:list):
        self.list_obj = list_obj
    def add_key(self,keyname):
        self.list_obj.append(keyname)
        print("添加成功！")
    def get_key(self,num):
        try:
            return self.list_obj[num-1]
        except:
            return f"要查看的元素不存在！"
    def update_list(self,list1):
        self.list_obj.extend(list1)
        return self.list_obj
    def del_key(self):
        reslut = self.list_obj.pop(len(self.list_obj)-1)
        return reslut
if __name__ == '__main__':
    l1 = Listinfo([11,22,33])
    l1.add_key(99)
    print(l1.get_key(2))
    print(l1.update_list([9999, 888]))
    print(l1.del_key())
    print(l1.del_key())

# 四、做一个学生点名系统，系统里支持：存入学生、更改学生、删除学生、点到学生姓名方法
# 存入学生（姓名、年龄、家庭地址、手机号）： 存入成功后，提示xxx存入成功
# 更改学生（姓名、年龄、家庭地址、手机号）：可以修改学生内容的任意一个字段
# 删除学生：删除的学生将不在展示
# 展示全部学生：可以看到全部的学生姓名
# 学生姓名：随机抽取任意一个存在的学生信息，然后打印：到！。举例： 刘闯到！
class StudentSystem:
    def insert_student(self,name,age,address,phone):
        str1 = f"学生姓名为：{name}，年龄：{age}，地址：{address}，手机号码：{phone}" + "\n"
        with open('student1.txt', 'r', encoding='utf-8') as f:
            all = f.readlines()
        if str1 not in all:
            with open('student1.txt', 'a', encoding='utf-8') as f:
                f.write(str1)
    def update_student(self,old_name,new_name):
        with open("student1.txt",'r',encoding='utf-8') as f:
            all_data = f.read()
        all_name = all_data.replace(old_name,new_name)
        with open('student1.txt','w',encoding='utf-8') as f:
            f.write(all_name)
    def delete_student(self,name):
        with open("student1.txt",'r',encoding='utf-8') as f:
            all_data = f.readlines()
        for i in all_data:
            if name in i:
                all_data.remove(i)
        with open("student1.txt",'w',encoding='utf-8') as f:
            f.writelines(all_data)
    def show_all_student(self):
        with open("student1.txt",'r',encoding='utf-8') as f:
            r = f.readlines()
        for i,k in enumerate(r):
            print(f"第{i+1}个的学生信息为：{k}")
    def chou_student(self,name):
        with open("student1.txt",'r',encoding='utf-8') as f:
            r = f.readlines()
        for i in r:
            if name in i:
                print(f"{name}到！")

if __name__ == '__main__':
    s1 = StudentSystem()
    s1.insert_student("张哦",19,"沈阳",'168788782')
    s1.insert_student("张1",19,"沈阳",'168788782')
    s1.insert_student("张2",19,"沈阳",'168788782')
    s1.show_all_student()

# 五、点餐管理系统
# 1》、餐馆可以新增菜品、下架菜品、修改菜品
# 2》、每个菜品，都有对应的库存，所有菜品的库存均为999，每出一道菜，库存-1
# 菜品有对应的价格，餐厅老板定义价格每道菜不允许超过15元，没有小数单位，均为整数
# 3》、餐馆后台有点赞系统，能够收集客户对菜品的喜好，0~5分
# 4》、有菜品评分提报功能，对平均分数（菜品总分/打分人数）低于3分的菜品进行强制下架；
class OrderingManagementSystem:
    def __init__(self):
        self.dishList = []
    def AddDish(self,Dish,price):
        if int(price) > 15:
            print("菜品价格超过15元！新增菜品失败！")
        else:
            dish = {Dish:{"价格":int(price),"库存":999,"点赞":[]}}
            self.dishList.append(dish)
    def LikeSystem(self,Dish,like:int):

        if like <=5 and like >=0:
            for i in self.dishList:

                if list(i.keys())[0] == Dish:

                    if i[Dish]['库存'] > 0:
                        i[Dish]['库存'] -=1
                        i[Dish]['点赞'].append(like)
                    else:
                        print("糟糕，您来晚了，菜已经售罄了！")
        else:
            print("点赞分数过高！请控制在0~5分！")
    def ReportDishRating(self):
        for i in self.dishList:
            if sum(i['点赞'])/len(i['点赞']) < 3:
                self.dishList.remove(i)
                print("菜品平均分数小于3分，强制下架！")
            else:
                pass

if __name__ == '__main__':
    o1 = OrderingManagementSystem()
    o1.AddDish("香辣肉丝",13)
    o1.AddDish("锅包肉",15)
    o1.AddDish("麻辣香锅",5)
    print(o1.dishList)
    o1.LikeSystem("锅包肉",5)
    print(o1.dishList)
# 六、定义一个桌子类（Desk），包含长（length）、宽（width）、高（height）属性，
# 包含一个打印桌子信息属性的方法（showInfo）。实例化2个桌子对象，为其赋予不同的属性值，
# 并调用showInfo方法，输出每个桌子的信息。
class Desk:
    def __init__(self,length,width,height):
        self.length = length
        self.width = width
        self.height = height
    def showInfo(self):
        print(f"桌子的长：{self.length},宽:{self.width},高：{self.height}")
if __name__ == '__main__':
    d1 = Desk(11,12,3)
    d2 = Desk(13,9,6)
    d1.showInfo()
    d2.showInfo()
# 七、定义一个用户类(User),用户名(username)和密码(password)是这个类的属性。
class User:
    username = "admin"
    password = "123456"
# 八、定义一个计算器类，有加减乘除四个方法
class Calculator:
    def __init__(self,num1,num2):
        self.num1 = num1
        self.num2 = num2
    def add(self):
        return self.num1+self.num2
    def subtract(self):
        return self.num1-self.num2
    def multiply(self):
        return self.num1*self.num2
    def divide(self):
        return self.num1 //self.num2
# 九、创建一个名为Person的类，具有以下属性和方法：
# 属性：name（姓名），age（年龄）
# 方法：greet()，打印出一句问候语，包括该人的姓名和年龄
class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def greet(self):
        print("大家好，我叫做：%s，今年%s岁"%(self.name,self.age))
if __name__ == '__main__':
    p1 = Person("张鑫",99)
    p1.greet()
# 十、定义一个图书管理系统类，图书可以新增、修改、删除，要求新增的每个图书都加到txt文本里，数据持久化
# 新增：图书名、作者名称、新建年月日
# 修改：图书名、作者名称、新建年月日
# 删除：图书删掉，且不在展示
# 查看：全量查询，精确查询，需要用户传入形参来控制返回结果
class BookManagementSystem:
    def addBook(self,BookName,AuthorName,CreateTime,ID):
        dict_book_obj = {BookName:{"作者名称":AuthorName,"创建时间":CreateTime,"图书ID":ID}}
        with open("book.txt",'r',encoding='utf-8') as f:
            all_data = f.read()
        if str(dict_book_obj) not in all_data:
            with open("book.txt",'a',encoding='utf-8') as f:
                f.write(str(dict_book_obj) + "\n")
                print("图书新增成功！")
        else:
            print("该图书已经存在了，无法重复新增！")
    def updateBook(self,BookName,NewBookName,AuthorName,NewAuthorName,CreateTime,NewCreateTime,ID,NewID):
        dict_book_obj = {BookName: {"作者名称": AuthorName, "创建时间": CreateTime,"图书ID":ID}}
        dict_book_new_obj = {NewBookName: {"作者名称": NewAuthorName, "创建时间": NewCreateTime,"图书ID":NewID}}
        with open("book.txt",'r',encoding='utf-8') as f:
            all_data = f.read()
        if str(dict_book_obj) not in all_data:
            print("图书不存在，修改失败！")
        else:
            new_all_data = all_data.replace(str(dict_book_obj),str(dict_book_new_obj))
            with open('book.txt','w',encoding='utf-8') as f:
                f.write(new_all_data)
                print("修改成功！")
    def deleteBook(self,BookName,ID):
        target = False
        with open("book.txt",'r',encoding='utf-8') as f:
            lines = f.readlines()
        for line in lines:
            if (f"{BookName}" in line) and (f"'图书ID': {ID}" in line) :
                target = True
                lines.remove(line)
        if target:
            with open('book.txt','w',encoding='utf-8') as f:
                f.writelines(lines)
                print("删除成功！")
        else:
            print("要删除的图书不存在，删除失败！")
    def searchBook(self,type,bookName):
        target = False
        with open("book.txt", 'r', encoding='utf-8') as f:
            all_data = f.readlines()
        if type == 1:
            for line in all_data:
                if line.split(': ')[0] == "{" + f"'{bookName}'" :
                    print("请耐心等待....")
                    time.sleep(2)
                    print("结果已经查出：")
                    print(line)
                    target = True
            if target == False:
                print(f"您要查询的：{bookName}不存在！")
        elif type == 2:
            for line in all_data:
                if bookName in line:
                    print("请耐心等待....")
                    time.sleep(2)
                    print("结果已经查出：")
                    print(line)
                    target =True
            if target == False:
                print(f"您要查询的：{bookName}不存在！")
# 十一、创建一个名为"Car"的类，该类具有"品牌"和"颜色"属性。
# 创建一个"start_engine"方法，该方法打印出"启动汽车引擎！"的消息。
# 创建一个"stop_engine"方法，该方法打印出"关闭汽车引擎！"的消息
class Car:
    def __init__(self,brand,color):
        self.brand = brand
        self.color = color
    def start_engine(self):
        print("汽车正在开火...")
        time.sleep(2)
        print("启动汽车引擎！")
    def stop_engine(self):
        print("关闭汽车引擎！")
# 十二、淘宝商家后台，可以上架商品、下架商品，功能如下：
#  （1） 可以添加商品，商家添加完的商品会存到商品列表
#  1.1  商品要有名称、sku、价格
#  （2） 可以修改商品信息：名称、sku、价格
#  （3） 可以对商品进行下架，下架后的商品不再展示
class Product:
    def __init__(self, name, sku, price):
        self.name = name
        self.sku = sku
        self.price = price
        self.is_active = True
    def update_info(self, name=None, sku=None, price=None):
        if name is not None:
            self.name = name
        if sku is not None:
            self.sku = sku
        if price is not None:
            self.price = price
    def deactivate(self):
        self.is_active = False
    def activate(self):
        self.is_active = True
    def __str__(self):
        status = "上架" if self.is_active else "下架"
        return f"商品名称: {self.name}, SKU: {self.sku}, 价格: {self.price}元, 状态: {status}"
class TaobaoSellerBackend:
    def __init__(self):
        self.products = []
        self.active_products = []
    def add_product(self, name, sku, price):
        product = Product(name, sku, price)
        self.products.append(product)
        self.active_products.append(product)
        print(f"成功添加商品: {name}")
    def update_product(self, sku, name=None, new_sku=None, price=None):
        for product in self.products:
            if product.sku == sku:
                product.update_info(name, new_sku, price)
                print(f"成功更新SKU为 {sku} 的商品信息")
                return
        print(f"未找到SKU为 {sku} 的商品")
    def deactivate_product(self, sku):
        for product in self.products:
            if product.sku == sku:
                product.deactivate()
                if product in self.active_products:
                    self.active_products.remove(product)
                print(f"成功下架SKU为 {sku} 的商品")
                return
        print(f"未找到SKU为 {sku} 的商品")
    def activate_product(self, sku):
        for product in self.products:
            if product.sku == sku and not product.is_active:
                product.activate()
                self.active_products.append(product)
                print(f"成功上架SKU为 {sku} 的商品")
                return
        print(f"未找到SKU为 {sku} 的下架商品")
    def list_active_products(self):
        print("\n当前上架商品列表:")
        if not self.active_products:
            print("暂无上架商品")
        for product in self.active_products:
            print(product)
    def list_all_products(self):
        print("\n所有商品列表:")
        if not self.products:
            print("暂无商品")
        for product in self.products:
            print(product)

if __name__ == "__main__":
    backend = TaobaoSellerBackend()
    backend.add_product("iPhone 13", "IP13-128-RED", 5999)
    backend.add_product("华为 Mate 40", "MATE40-256-BLUE", 4999)
    backend.add_product("小米 12", "MI12-128-BLACK", 3699)

    backend.list_active_products()

    backend.update_product("IP13-128-RED", price=5799)
    backend.update_product("MATE40-256-BLUE", name="华为 Mate 40 Pro")

    backend.deactivate_product("MI12-128-BLACK")

    backend.list_active_products()
    backend.list_all_products()

    backend.activate_product("MI12-128-BLACK")
    backend.list_active_products()
# 十三、定义一个人类
# 1.小明和小美都爱跑步
# 2.小美体重45.0公斤
# 3.小明体重75.0公斤
# 4.每次跑步都会减少0.5公斤
# 5.每次吃东西都会增加1公斤
class Person:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def run(self):
        self.weight -= 0.5
        print(f"{self.name}跑步一次，体重减到{self.weight}公斤")

    def eat(self):
        self.weight += 1
        print(f"{self.name}吃东西一次，体重增加到{self.weight}公斤")

    def __str__(self):
        return f"姓名: {self.name}, 体重: {self.weight}公斤"

xiaoming = Person("小明", 75.0)
xiaomei = Person("小美", 45.0)

print("初始状态:")
print(xiaoming)
print(xiaomei)

xiaoming.run()
xiaoming.run()

xiaomei.eat()

print("\n活动后的状态:")
print(xiaoming)
print(xiaomei)
# 十四、士兵瑞恩有一把ak47
# 士兵可以开火（开火扣动的是扳机）
# 枪能够发射子弹（把子弹打出去）
# 抢能够装子弹–增加子弹数量
# 要求没子弹，需要输出没有子弹了，且发射失败
class Gun:
    def __init__(self, name, max_bullets):
        self.name = name
        self.max_bullets = max_bullets
        self.bullet_count = 0

    def add_bullets(self, num):
        if self.bullet_count + num > self.max_bullets:
            added = self.max_bullets - self.bullet_count
            self.bullet_count = self.max_bullets
            print(f"{self.name}装弹: 只能装入{added}发，弹夹已满({self.max_bullets}发)")
        else:
            self.bullet_count += num
            print(f"{self.name}装弹: 装入{num}发，当前{self.bullet_count}发")

    def shoot(self):
        if self.bullet_count <= 0:
            print(f"{self.name}发射失败: 弹夹空了!")
            return False

        self.bullet_count -= 1
        print(f"{self.name}发射子弹: 砰! 剩余{self.bullet_count}发")
        return True

    def __str__(self):
        return f"{self.name}: {self.bullet_count}/{self.max_bullets}发"


class Soldier:
    def __init__(self, name):
        self.name = name
        self.gun = None

    def equip_gun(self, gun):
        self.gun = gun
        print(f"{self.name}装备了{gun.name}")

    def fire(self):
        if not self.gun:
            print(f"{self.name}开火失败: 没有装备枪支!")
            return False

        print(f"{self.name}扣动扳机...")
        return self.gun.shoot()

    def reload(self, num):
        if not self.gun:
            print(f"{self.name}装弹失败: 没有装备枪支!")
            return

        self.gun.add_bullets(num)

    def __str__(self):
        gun_info = f"，装备{self.gun}" if self.gun else "，未装备武器"
        return f"士兵{self.name}{gun_info}"


# 使用示例
if __name__ == "__main__":
    # 创建AK47(弹夹容量30发)
    ak47 = Gun("AK47", 30)

    # 创建士兵瑞恩
    ryan = Soldier("瑞恩")
    print(ryan)

    # 瑞恩装备AK47
    ryan.equip_gun(ak47)
    print(ryan)

    # 装填子弹
    ryan.reload(10)  # 装入10发
    ryan.reload(25)  # 尝试装入25发，但只能装入20发(因为弹夹容量30发)

    # 开火
    for _ in range(5):
        ryan.fire()

    # 打光子弹
    for _ in range(30):
        ryan.fire()  # 最后会提示弹夹空了

    # 重新装弹
    ryan.reload(15)
    for _ in range(3):
        ryan.fire()

